<template>
	<view class="order-detail-container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="back-btn" @click="goBack">
				<image src="/static/icon/导航.png" class="back-icon" />
			</view>
			<text class="title">订单详情</text>
			<view class="right-placeholder"></view>
		</view>
		
		<!-- 订单状态 -->
		<view class="status-card">
			<view class="status-header">
				<text class="status-text" :class="statusClass">{{statusText}}</text>
			</view>
			<view class="status-content">
				<view class="countdown" v-if="order.status === 'pending'">
					<text>支付倒计时：{{countdownText}}</text>
				</view>
				<view class="status-desc">
					<text>{{statusDescription}}</text>
				</view>
			</view>
		</view>
		
		<!-- 订单信息 -->
		<view class="order-info-card">
			<view class="card-title">订单信息</view>
			<view class="info-item">
				<text class="item-label">订单编号</text>
				<text class="item-value">{{order.order_no || ''}}</text>
			</view>
			<view class="info-item">
				<text class="item-label">下单时间</text>
				<text class="item-value">{{formatTime(order.create_time) || ''}}</text>
			</view>
			<view class="info-item" v-if="order.payment_time">
				<text class="item-label">支付时间</text>
				<text class="item-value">{{formatTime(order.payment_time) || ''}}</text>
			</view>
			<view class="info-item">
				<text class="item-label">支付方式</text>
				<text class="item-value">{{paymentMethod}}</text>
			</view>
		</view>
		
		<!-- 订单内容 -->
		<view class="order-content-card">
			<view class="card-title">订单内容</view>
			<view class="order-goods">
				<view class="goods-name">{{getOrderTitle()}}</view>
				<view class="goods-price">¥ {{order.amount || '0.00'}}</view>
			</view>
			<view class="goods-detail" v-if="order.room_name">
				<view class="detail-item">
					<text class="detail-label">房间</text>
					<text class="detail-value">{{order.room_name}}</text>
				</view>
			</view>
			<view class="goods-detail" v-if="order.reservation_time">
				<view class="detail-item">
					<text class="detail-label">预订时间</text>
					<text class="detail-value">{{formatTime(order.reservation_time)}}</text>
				</view>
			</view>
			<view class="goods-detail" v-if="order.duration">
				<view class="detail-item">
					<text class="detail-label">时长</text>
					<text class="detail-value">{{order.duration}}小时</text>
				</view>
			</view>
			<view class="goods-detail" v-if="order.remark && order.order_type === 'recharge' && order.remark.includes('购买优惠券')">
				<view class="detail-item">
					<text class="detail-label">优惠券详情</text>
					<text class="detail-value">{{formatCouponRemark(order.remark)}}</text>
				</view>
			</view>
			<view class="price-detail">
				<view class="price-item">
					<text class="price-label">订单金额</text>
					<text class="price-value">¥ {{order.amount || '0.00'}}</text>
				</view>
				<view class="price-item" v-if="order.discount">
					<text class="price-label">优惠金额</text>
					<text class="price-value">- ¥ {{order.discount || '0.00'}}</text>
				</view>
				<view class="price-item total">
					<text class="price-label">实付金额</text>
					<text class="price-value highlight">¥ {{order.actual_amount || order.amount || '0.00'}}</text>
				</view>
			</view>
		</view>
		
		<!-- 底部操作栏 -->
		<view class="action-bar" v-if="order.status">
			<!-- 未支付订单 -->
			<block v-if="order.status === 'pending'">
				<button class="action-btn primary" @click="goToPay">立即支付</button>
				<button class="action-btn secondary" @click="cancelOrder">取消订单</button>
			</block>
			
			<!-- 已支付订单 -->
			<block v-if="order.status === 'paid'">
				<button class="action-btn secondary" @click="contactService">联系客服</button>
			</block>
			
			<!-- 已取消订单 -->
			<block v-if="order.status === 'canceled'">
				<button class="action-btn primary" @click="createNewOrder">再次预订</button>
			</block>
		</view>
	</view>
</template>

<script>
import request from '@/utils/request.js';

export default {
	data() {
		return {
			id: '', // 订单ID
			order: {}, // 订单数据
			countdown: 0, // 支付倒计时（秒）
			timer: null, // 倒计时定时器
		};
	},
	computed: {
		// 订单状态文本
		statusText() {
			const statusMap = {
				'pending': '待支付',
				'paid': '已支付',
				'canceled': '已取消',
				'expired': '已过期',
				'completed': '已完成'
			};
			return statusMap[this.order.status] || '未知状态';
		},
		// 订单状态描述
		statusDescription() {
			const statusMap = {
				'pending': '请在15分钟内完成支付，超时订单将自动取消',
				'paid': '您的订单已支付成功，可前往棋牌室消费',
				'canceled': '订单已取消',
				'expired': '订单已过期',
				'completed': '订单已完成，感谢您的使用'
			};
			return statusMap[this.order.status] || '';
		},
		// 订单状态样式
		statusClass() {
			const statusMap = {
				'pending': 'warning',
				'paid': 'success',
				'canceled': 'danger',
				'expired': 'danger',
				'completed': 'success'
			};
			return statusMap[this.order.status] || '';
		},
		// 支付方式
		paymentMethod() {
			const methodMap = {
				'wechat': '微信支付',
				'balance': '余额支付',
				'alipay': '支付宝',
				'': '未支付'
			};
			return methodMap[this.order.payment_method] || '未支付';
		},
		// 倒计时文本
		countdownText() {
			if (this.countdown <= 0) return '00:00';
			const minutes = Math.floor(this.countdown / 60);
			const seconds = this.countdown % 60;
			return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
		}
	},
	onLoad(options) {
		// 获取订单ID
		this.id = options.id || '';
		
		if (!this.id) {
			uni.showToast({
				title: '订单ID不能为空',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
			return;
		}
		
		// 加载订单详情
		this.loadOrderDetail();
	},
	onUnload() {
		// 清除定时器
		if (this.timer) {
			clearInterval(this.timer);
			this.timer = null;
		}
	},
	methods: {
		/**
		 * 加载订单详情
		 */
		async loadOrderDetail() {
			try {
				uni.showLoading({
					title: '加载中...'
				});
				
				const res = await request.get(`/api/mobile/order/detail?orderId=${this.id}`);
				
				uni.hideLoading();
				
				if (res.code === 200 && res.data) {
					this.order = res.data;
					
					// 如果是待支付状态，开始倒计时
					if (this.order.status === 'pending') {
						this.startCountdown();
					}
				} else {
					uni.showToast({
						title: '获取订单详情失败',
						icon: 'none'
					});
				}
			} catch (error) {
				uni.hideLoading();
				console.error('获取订单详情失败:', error);
				uni.showToast({
					title: '获取订单详情失败',
					icon: 'none'
				});
			}
		},
		
		/**
		 * 开始倒计时
		 */
		startCountdown() {
			// 清除已有定时器
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
			
			// 计算剩余支付时间（假设15分钟支付时间）
			let createTime;
			try {
				// 尝试多种日期格式解析
				if (!this.order.create_time) {
					this.countdown = 0;
					return;
				}
				
				// 处理可能的格式问题
				if (typeof this.order.create_time === 'string') {
					// 尝试标准ISO格式
					if (this.order.create_time.includes('T') || this.order.create_time.includes('Z')) {
						createTime = new Date(this.order.create_time).getTime();
					} else {
						// 尝试处理 YYYY-MM-DD HH:MM:SS 格式
						const parts = this.order.create_time.replace(/-/g, '/').split('.')[0];
						createTime = new Date(parts).getTime();
					}
				} else {
					// 如果是Date对象或者时间戳
					createTime = new Date(this.order.create_time).getTime();
				}
				
				// 验证createTime是否有效
				if (isNaN(createTime)) {
					console.error('无效的时间格式:', this.order.create_time);
					this.countdown = 0;
					return;
				}
			} catch (e) {
				console.error('解析订单创建时间出错:', e, this.order.create_time);
				this.countdown = 0;
				return;
			}
			
			const now = Date.now();
			const expireTime = createTime + 15 * 60 * 1000; // 15分钟过期
			
			// 计算剩余秒数
			let remainSeconds = Math.floor((expireTime - now) / 1000);
			
			// 如果已过期，设置倒计时为0
			if (remainSeconds <= 0) {
				this.countdown = 0;
				return;
			}
			
			// 设置初始倒计时
			this.countdown = remainSeconds;
			
			// 启动定时器，每秒更新倒计时
			this.timer = setInterval(() => {
				this.countdown--;
				
				// 倒计时结束
				if (this.countdown <= 0) {
					clearInterval(this.timer);
					this.timer = null;
					
					// 刷新订单状态
					this.loadOrderDetail();
				}
			}, 1000);
		},
		
		/**
		 * 格式化时间
		 */
		formatTime(time) {
			if (!time) return '';
			
			try {
				let date;
				
				// 处理可能的格式问题
				if (typeof time === 'string') {
					// 尝试标准ISO格式
					if (time.includes('T') || time.includes('Z')) {
						date = new Date(time);
					} else {
						// 尝试处理 YYYY-MM-DD HH:MM:SS 格式
						const parts = time.replace(/-/g, '/').split('.')[0];
						date = new Date(parts);
					}
				} else {
					// 如果是Date对象或者时间戳
					date = new Date(time);
				}
				
				// 验证日期是否有效
				if (isNaN(date.getTime())) {
					console.error('无效的时间格式:', time);
					return '';
				}
				
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hour = date.getHours().toString().padStart(2, '0');
				const minute = date.getMinutes().toString().padStart(2, '0');
				
				return `${year}-${month}-${day} ${hour}:${minute}`;
			} catch (e) {
				console.error('格式化时间出错:', e, time);
				return '';
			}
		},
		
		/**
		 * 返回上一页
		 */
		goBack() {
			uni.navigateBack();
		},
		
		/**
		 * 前往支付
		 */
		goToPay() {
			uni.navigateTo({
				url: `/pages/payment/payment?type=order&id=${this.id}`
			});
		},
		
		/**
		 * 取消订单
		 */
		cancelOrder() {
			uni.showModal({
				title: '取消订单',
				content: '确定要取消该订单吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							uni.showLoading({
								title: '处理中...'
							});
							
							const result = await request.post(`/api/mobile/order/cancel/${this.id}`);
							
							uni.hideLoading();
							
							if (result.code === 200) {
								uni.showToast({
									title: '订单已取消',
									icon: 'success'
								});
								
								// 更新订单状态
								this.order.status = 'canceled';
							} else {
								uni.showToast({
									title: result.message || '取消订单失败',
									icon: 'none'
								});
							}
						} catch (error) {
							uni.hideLoading();
							console.error('取消订单失败:', error);
							uni.showToast({
								title: '取消订单失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		/**
		 * 联系客服
		 */
		contactService() {
			uni.showToast({
				title: '联系客服功能暂未开放',
				icon: 'none'
			});
		},
		
		/**
		 * 再次预订
		 */
		createNewOrder() {
			uni.navigateTo({
				url: '/pages/index/index'
			});
		},
		
		/**
		 * 获取订单标题
		 */
		getOrderTitle() {
			// 如果有明确的标题，优先使用
			if (this.order.title) {
				return this.order.title;
			}
			
			// 根据订单类型和备注确定标题
			if (this.order.order_type === 'recharge') {
				// 如果备注包含"购买优惠券"，说明是购买优惠券的订单
				if (this.order.remark && this.order.remark.includes('购买优惠券')) {
					return '优惠券购买';
				}
				return '账户充值';
			} else if (this.order.order_type === 'reservation') {
				return '棋牌室预订';
			} else if (this.order.order_type === 'coupon') {
				return '优惠券购买';
			}
			
			// 默认标题
			return this.order.order_type || '未知订单';
		},
		
		/**
		 * 格式化优惠券备注信息，移除ID
		 */
		formatCouponRemark(remark) {
			if (!remark) return '';
			
			// 移除包含ID的部分
			// 处理常见的ID格式: "(ID: 123)"、"（ID：123）"、"ID: 123" 等
			let formattedRemark = remark.replace(/[\(（]ID[:：]\s*\d+[\)）]/g, '')
				.replace(/ID[:：]\s*\d+/g, '')
				.replace(/\s+/g, ' ')
				.trim();
			
			// 如果备注中只包含"购买优惠券"信息，则返回优化后的描述
			if (formattedRemark.includes('购买优惠券') && formattedRemark.length < 15) {
				return '优惠券套餐';
			}
			
			return formattedRemark;
		}
	}
}
</script>

<style>
page {
	background-color: #f5f5f5;
	min-height: 100%;
}

.order-detail-container {
	display: flex;
	flex-direction: column;
	padding-bottom: 120rpx;
}

/* 顶部导航 */
.header {
	height: 180rpx;
	background-color: #7FB992;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 80rpx 30rpx 0;
}

.back-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
}

.back-icon {
	width: 40rpx;
	height: 40rpx;
	transform: rotate(180deg);
}

.title {
	color: #FFFFFF;
	font-size: 36rpx;
	font-weight: 500;
}

.right-placeholder {
	width: 60rpx;
}

/* 订单状态卡片 */
.status-card {
	margin: 30rpx;
	background-color: #FFFFFF;
	border-radius: 16rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.status-header {
	padding: 30rpx;
	background-color: #F8F8F8;
}

.status-text {
	font-size: 34rpx;
	font-weight: 500;
}

.status-text.success {
	color: #7FB992;
}

.status-text.warning {
	color: #FF9900;
}

.status-text.danger {
	color: #FF6B6B;
}

.status-content {
	padding: 30rpx;
}

.countdown {
	color: #FF6B6B;
	font-size: 28rpx;
	margin-bottom: 10rpx;
}

.status-desc {
	font-size: 26rpx;
	color: #999999;
}

/* 订单信息卡片 */
.order-info-card, .order-content-card {
	margin: 30rpx;
	background-color: #FFFFFF;
	border-radius: 16rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.card-title {
	font-size: 30rpx;
	font-weight: 500;
	color: #333333;
	margin-bottom: 20rpx;
}

.info-item {
	display: flex;
	justify-content: space-between;
	margin: 20rpx 0;
}

.item-label {
	font-size: 28rpx;
	color: #999999;
}

.item-value {
	font-size: 28rpx;
	color: #333333;
}

/* 订单内容 */
.order-goods {
	display: flex;
	justify-content: space-between;
	padding: 20rpx 0;
	border-bottom: 1px solid #F5F5F5;
}

.goods-name {
	font-size: 30rpx;
	color: #333333;
}

.goods-price {
	font-size: 30rpx;
	color: #333333;
	font-weight: 500;
}

.goods-detail {
	padding: 20rpx 0;
	border-bottom: 1px solid #F5F5F5;
}

.detail-item {
	display: flex;
	justify-content: space-between;
	margin: 10rpx 0;
}

.detail-label {
	font-size: 26rpx;
	color: #999999;
}

.detail-value {
	font-size: 26rpx;
	color: #333333;
}

.price-detail {
	padding-top: 20rpx;
}

.price-item {
	display: flex;
	justify-content: space-between;
	margin: 10rpx 0;
}

.price-label {
	font-size: 28rpx;
	color: #999999;
}

.price-value {
	font-size: 28rpx;
	color: #333333;
}

.price-item.total {
	margin-top: 20rpx;
	padding-top: 20rpx;
	border-top: 1px dashed #F5F5F5;
}

.price-value.highlight {
	color: #FF6B6B;
	font-size: 32rpx;
	font-weight: 500;
}

/* 底部操作栏 */
.action-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 20rpx 30rpx;
	background-color: #FFFFFF;
	display: flex;
	justify-content: flex-end;
	gap: 20rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.action-btn {
	width: 220rpx;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	border-radius: 40rpx;
	font-size: 28rpx;
}

.action-btn.primary {
	background-color: #7FB992;
	color: #FFFFFF;
}

.action-btn.secondary {
	background-color: #F5F5F5;
	color: #666666;
	border: 1px solid #E0E0E0;
}
</style> 